// 判断是否URL
const isUrl = function(str) {
	let v = new RegExp(
		'^(?!mailto:)(?:(?:http|https|ftp)://|//)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$',
		'i');
	return v.test(str);
}

const zeroFill = function(num) {
	return num < 10 ? '0' + num : num;
}

// 模仿php 时间格式化
const dateFormat = function(fmt, time) {
	let date = new Date();
	if (time) {
		date.setTime(time);
	}

	let o = {
		"Y": date.getFullYear(),
		"m": zeroFill(date.getMonth() + 1),
		"d": zeroFill(date.getDate()),
		"H": zeroFill(date.getHours()),
		"i": zeroFill(date.getMinutes()),
		"s": zeroFill(date.getSeconds()),
	};
	for (let k in o) {
		if (fmt.indexOf(k) > -1) {
			fmt = fmt.replace(new RegExp("(" + k + ")"), o[k]);
		}
	}
	return fmt;
}

// 获取 url 的参数值
const getUrlParam = function(url, name) {

	if (url.indexOf('?') > -1) {
		url = url.replace('?', '&');
		let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
		let r = url.match(reg);
		if (r != null) return decodeURI(r[2]);
	} else {
		let arr = url.split('/');
		for (let i = 0, len = arr.length; i < len; i++) {
			if (arr[i] === name) {
				return arr[i + 1]
			}
		}
	}
	return null;
}


// 去掉不可见内容
const removeInvisible = function(content) {
	return content.replaceAll(/>\s*</ig, '');
}
// 获取url 的域名部分， http://www.wansh.cc
const getUrlHost = function(url) {
	let arr = url.split('/');
	return arr[0] + arr[1] + '//' + arr[2];
}

// 有网络的情况下初始化数据
const initData = function(call) {
	uni.getNetworkType({
		success: function(res) {
			if (res.networkType == 'none') {
				uni.onNetworkStatusChange(function(res) {
					if (res.isConnected) {
						call();
					}
				});
				uni.showModal({
					showCancel: false,
					title: '暂无网络',
					content: '请检查网络是否启用'
				})
			} else {
				call();
			}
		}
	});
}
const inArray = function(arr, field, val) {
	for (var i = 0, len = arr.length; i < len; i++) {
		let item = arr[i];
		if (field) {
			if (item[field] == val) {
				return i;
			}
		} else {
			if (item == val) {
				return i;
			}
		}
	}
	return -1;
}


module.exports = {
	isUrl,
	dateFormat,
	getUrlParam,
	removeInvisible,
	getUrlHost,
	initData,
	inArray,
	zeroFill,
}
